package com.oren.system.service.imp;

import com.oren.base.pojo.Tree;
import com.oren.system.mapper.DepartmentMapper;
import com.oren.system.pojo.Department;
import com.oren.system.pojo.TreeEntity;
import com.oren.system.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wsw
 * @Description:
 * @Date: Create on 2018/7/29 15:25
 */
@Service
@Transactional
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Tree> getDepartmentTree() throws Exception {
        List<Tree> listTree=new ArrayList<Tree>();
        //获取顶级
        Department department=departmentMapper.findDeParent();
        Tree tree=new Tree();
        tree.setId(String.valueOf(department.getId()));
        tree.setText(department.getName());
        //获取子
        List<Department> listChild= departmentMapper.findDeChild(department.getId());
        tree.setChildren(getTree(listChild));
        listTree.add(tree);
        return listTree;
    }

    //递归查询所有的部门
    public List<Tree> getTree( List<Department> list) throws Exception {
        List<Tree> listTree=new ArrayList<Tree>();
        if(list!=null && list.size()>0){
            for (Department department:list) {
                Tree tree=new Tree();
                tree.setId(String.valueOf(department.getId()));
                tree.setText(department.getName());
                 List<Department> listChild= departmentMapper.findDeChild(department.getId());
                List<Tree> listChildTree=new ArrayList<>();
                if(listChild!=null && listChild.size()>0){
                    listChildTree=  getTree(listChild);
                }
                tree.setChildren(listChildTree);
                listTree.add(tree);
            }
        }
        return listTree;
    }


    @Override
    public int deleteEntity(Integer id) throws Exception {
        return departmentMapper.deleteDepartment(id);
    }

    @Override
    public int updaetEntity(Department department) throws Exception {
        return departmentMapper.updateDepartment(department);
    }

    @Override
    public int insertEntity(Department department) throws Exception {
        return departmentMapper.insertDepartment(department);
    }
}
